package flex.cc.basicinformation.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.base.enums.ErrorCodeEnum;
import flex.cc.basicinformation.dao.ChannelDao;
import flex.cc.basicinformation.dao.ChannelDataDao;
import flex.cc.basicinformation.entity.ChannelDataEntity;
import flex.cc.basicinformation.entity.ChannelEntity;
import flex.cc.basicinformation.service.ChannelService;
import flex.cc.basicinformation.vo.ChannelVo;
import flex.cc.basicinformation.vo.DynamicItem;
import flex.cc.system.dao.DictCodeDao;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.uac.exceptions.UacBizException;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("ChannelServiceImpl")
@Slf4j
public class ChannelServiceImpl extends ServiceImpl<ChannelDao, ChannelEntity> implements ChannelService {

    @Autowired
	private ChannelDao channeDao;

    @Autowired
	private ChannelDataDao channelDataDao;

    @Autowired
	private DictCodeDao dictCodeDao;

    @Override
	public IPage<ChannelEntity> queryChannelPage(ChannelEntity channe) {
    	List<String> listItem=new ArrayList<String>();
		 if(!PublicUtil.isEmpty(channe.getServiceItem())) {
			 StringTokenizer st=new StringTokenizer(channe.getServiceItem(),",");
				while(st.hasMoreTokens()){
					listItem.add(st.nextToken());
		        }
		 }
		channe.setServiceItemList(listItem);
		IPage<ChannelEntity> page = channeDao.queryChannelPage(new Page(channe.getPageNum(),channe.getPageSize()),channe);
		List<ChannelEntity> list= page.getRecords();
		if (list!=null&&list.size()>0) {
			Map<String,String> map=new HashMap<String,String>();
			Map<String,String> map1=new HashMap<String,String>();
			List<String> lists=new ArrayList<String>();
			for(ChannelEntity channeinfo:list) {
				lists.add(channeinfo.getId()+"");
			}
			List<ChannelDataEntity> urlList= channelDataDao.getUrl(this.getSqlInString(lists));
			DictCodeEntity code=new DictCodeEntity();
			code.setTypeCode("serviceItem");
			List<DictCodeEntity> dictList = dictCodeDao.getdictCodeList(code);
			if(dictList!=null&&dictList.size()>0) {
				for (DictCodeEntity d : dictList) {
					map1.put(d.getCode(),d.getValue());
				}
			}
			for (ChannelDataEntity url : urlList) {
				map.put(url.getYwid(),url.getUrl());
			}
			for(ChannelEntity channeinfo:list) {
				channeinfo.setUrl(map.get(channeinfo.getId()+""));
				if(!PublicUtil.isEmpty(channeinfo.getChannelCode())) {
					channeinfo.setChannelName(channeinfo.getChannelName()+"("+channeinfo.getChannelCode()+")");
				}
				if(!PublicUtil.isEmpty(channeinfo.getServiceItem()) ) {
					String[] serviceItem=channeinfo.getServiceItem().split(",");
					String cbkind="";
					for(int i = 0; i < serviceItem.length; i++) {
	   	    			if(i == serviceItem.length-1){
	   	    				cbkind += map1.get(serviceItem[i]) ;
	   	  			    }else{
	   	  			    	cbkind += map1.get(serviceItem[i]) + "," ;
	   	  			    }
	   	    		 }
					channeinfo.setServiceItem(cbkind);
				}
			}
		}

		return page;
	}

	@Override
	public void saveChannel(ChannelEntity channe, LoginAuthDto loginAuthDto) {
		if(PublicUtil.isEmpty(channe.getId())) {
			Date currentDate = new Date();
			List<ChannelEntity>channelList=channeDao.selectChanneName(channe);
			if(channelList!=null&&channelList.size()>0){
				 throw new UacBizException(ErrorCodeEnum.CHANNE10011025, channe.getChannelName());
			}else {
				String urlType=	removaDuplicate(channe.getDynamicItem());
				if("1".equals(urlType)) {
					throw new UacBizException(ErrorCodeEnum.CHANNE10011026, "");
				}

				channe.setCreateTime(currentDate);
				channe.setCreater(loginAuthDto.getUserCode());
				channe.setUpdateTime(currentDate);
				channe.setUpdater(loginAuthDto.getUserCode());
				channe.setStatus("1"); /** 2022/02/25 0025 9:31 【2.2-服务包配置需求】 渠道商编辑：优化保存操作，给状态status赋值1-有效，即启用 */
				channeDao.insertChannel(channe);
				String id=channe.getId()+"";
				List<DynamicItem> list=channe.getDynamicItem();
				for(int i=0;i<list.size();i++) {
					ChannelDataEntity data=new ChannelDataEntity();

					data.setCreateTime(currentDate);
					data.setCreater(loginAuthDto.getUserCode());
					data.setUpdateTime(currentDate);
					data.setUpdater(loginAuthDto.getUserCode());
					data.setUrl(list.get(i).getUrl());;
					data.setUrlType(list.get(i).getUrlType());
					data.setYwid(id);
					data.setUpdateInfo(loginAuthDto);
					channelDataDao.insertChannelData(data);
				}
			}
		}else {
			/** 2022/02/25 0025 9:36 【2.2-服务包配置需求】渠道商编辑  */
			Date currentDate = new Date();
			// 查询一个渠道商
			Map<String, Object> channelParams = new HashMap<>();
			channelParams.put("id", channe.getId());
			ChannelEntity channelEntity = channeDao.getOneByParams(channelParams);
			List<ChannelEntity> channelList = channeDao.selectChanneName(channe);
			boolean remove = channelList.remove(channelEntity); // list除去根据id查询到的渠道商，若还有，则判断为重复

			if(channelList != null && channelList.size() > 0) {
				throw new UacBizException(ErrorCodeEnum.CHANNE10011025, channe.getChannelName());
			} else {
				String urlType=	removaDuplicate(channe.getDynamicItem()); // 判断接口是否重复
				if("1".equals(urlType)) {
					throw new UacBizException(ErrorCodeEnum.CHANNE10011026, "");
				}

				channelEntity.setChannelCode(channe.getChannelCode());
				channelEntity.setChannelName(channe.getChannelName());
				channelEntity.setServiceItem(channe.getServiceItem());
				channelEntity.setPk(channe.getPk());
				channelEntity.setSk(channe.getSk());
				channelEntity.setStatus(channe.getStatus());

				channelEntity.setUpdater(loginAuthDto.getUserCode());
				channelEntity.setUpdateTime(currentDate);
				channelEntity.setClientId(channe.getClientId());

				channeDao.updateById(channelEntity);

				String id = Long.toString(channe.getId());
				// 删除已有的，将新的重新保存。
				int deleteByYwid = channelDataDao.deleteByYwid(id);
				List<DynamicItem> list = channe.getDynamicItem();
				for(int i=0; i<list.size(); i++) {
					ChannelDataEntity data=new ChannelDataEntity();

					data.setCreateTime(currentDate);
					data.setCreater(loginAuthDto.getUserCode());
					data.setUpdateTime(currentDate);
					data.setUpdater(loginAuthDto.getUserCode());
					data.setUrl(list.get(i).getUrl());;
					data.setUrlType(list.get(i).getUrlType());
					data.setYwid(id);
					data.setUpdateInfo(loginAuthDto);
					channelDataDao.insertChannelData(data);
				}
			}

		}
	}

	@Override
	public String getChannelName(String channelName, String id) {
		// 查询一个渠道商
		Map<String, Object> channelParams = new HashMap<>();
		channelParams.put("id", id);
		ChannelEntity channelEntity = channeDao.getOneByParams(channelParams);

		ChannelEntity channel = new ChannelEntity();
		channel.setChannelName(channelName);
		List<ChannelEntity> channelList = channeDao.selectChanneName(channel);

		boolean remove = channelList.remove(channelEntity); // list除去根据id查询到的渠道商，若还有，则判断为重复

		String result="";
		if(channelList != null && channelList.size() > 0) {
			result = "1";
		} else {
			result = "0";
		}
		return result;
	}


	@Override
	public String getChannelCode(String channelCode, String id) {
		// 查询一个渠道商
		Map<String, Object> channelParams = new HashMap<>();
		channelParams.put("id", id);
		ChannelEntity channelEntity = channeDao.getOneByParams(channelParams);

		ChannelEntity channel = new ChannelEntity();
		channel.setChannelCode(channelCode);
		List<ChannelEntity> channelList = channeDao.selectChanneName(channel);

		boolean remove = channelList.remove(channelEntity); // list除去根据id查询到的渠道商，若还有，则判断为重复

		String result="";
		if(channelList != null && channelList.size() > 0) {
			result = "1";
		} else {
			result = "0";
		}
		return result;
	}

	public String  removaDuplicate(List<DynamicItem> list){
		String temp = "";
        for (int i = 0; i < list.size() - 1; i++){
            temp = list.get(i).getUrlType();
            for (int j = i + 1; j < list.size(); j++) {
                if (temp.equals(list.get(j).getUrlType())){
                    System.out.println("第" + (i + 1) + "个跟第" + (j + 1) + "个重复，值是：" + temp);
                    return "1";
                }
            }
        }
		return "0";
	}

	public  String getSqlInString(List<String> values){
		if(PublicUtil.isEmpty(values) ) return "";
		StringBuffer res =  new StringBuffer("(");
		int firstFlag = 1;
		for(String val : values){
			if(firstFlag == 1){
				res.append("'").append(val).append("'");
				firstFlag = 0;
			}else{
				res.append(",'").append(val).append("'");
			}
		}
		res.append(")");
		return res.toString();
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年10月19日下午3:20:28
	 * @desc 根据map参数查询实体信息
	 */
	@Override
	public List<ChannelEntity> findChannelByParam(Map<String, String> channelMap) {
		return channeDao.findChannelByParam(channelMap);
	}

	@Override
	public List<ChannelEntity> getAllChannelName() {
		return channeDao.getAllChannelName();
	}

	@Override
	public ChannelEntity getChannelDetail(Long id) {
		ChannelEntity channe=channeDao.selectById(id);
		List<DynamicItem> list=new ArrayList<DynamicItem>();
		List<ChannelDataEntity> channelData=channelDataDao.selectChannelDataById(id+"");
		for(ChannelDataEntity data:channelData) {
			DynamicItem dynamic=new DynamicItem();
			dynamic.setUrl(data.getUrl());
			dynamic.setUrlType(data.getUrlType());
			channelData.add(data);
		}
		channe.setDynamicItem(list);
		return channe;
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年10月26日下午4:02:15
	 * @desc 根据渠道商Id查询接口地址信息
	 */
	@Override
	public List<ChannelDataEntity> queryListByYwId(String channelId) {
		return channelDataDao.selectChannelDataById(channelId);
	}

	/**
	 * @param params 请求参数
	 * @return
	 * @description 根据参数查询一个渠道商信息【2.2-服务包配置需求】
	 * @author wkangle
	 * @time 2022/02/23 0023 15:55
	 * @exception/throws
	 */
	@Override
	public ChannelEntity getOneByParams(Map<String, Object> params) {
		return channeDao.getOneByParams(params);
	}

	/**
	 * @param id 渠道商主键
	 * @return
	 * @description 修改渠道商状态【2.2-服务包配置需求】
	 * @author wkangle
	 * @time 2022/02/23 0023 17:53
	 * @exception/throws
	 */
	@Override
	public Map<String, String> switchStatus(Long id, String status) {
		Map<String, String> result = new HashMap<>();
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		ChannelEntity oneByParams = channeDao.getOneByParams(params);
		if (PublicUtil.isEmpty(oneByParams)) {
			result.put("code", "0001");
			result.put("message", "渠道商不存在");
			return result;
		}
		if ("1".equals(status)) { // 启用
			String dbStatus = oneByParams.getStatus();
			if ("1".equals(dbStatus)) {
				result.put("code", "0001");
				result.put("message", "渠道商(" + oneByParams.getChannelName() + ")已是启用状态");
				return result;
			} else {
				try {
					oneByParams.setStatus("1");
					channeDao.updateById(oneByParams);

					result.put("code", "0000");
					result.put("message", "渠道商(" + oneByParams.getChannelName() + ")启用成功");
					return result;
				} catch (Exception e) {
					e.printStackTrace();
					result.put("code", "0001");
					result.put("message", "渠道商(" + oneByParams.getChannelName() + ")启用失败，原因：" + e.getMessage());
					return result;
				}
			}
		} else { // 禁用
			String dbStatus = oneByParams.getStatus();
			if ("0".equals(dbStatus)) {
				result.put("code", "0001");
				result.put("message", "渠道商(" + oneByParams.getChannelName() + ")已是禁用状态");
				return result;
			} else {
				try {
					oneByParams.setStatus("0");
					channeDao.updateById(oneByParams);

					result.put("code", "0000");
					result.put("message", "渠道商(" + oneByParams.getChannelName() + ")禁用成功");
					return result;
				} catch (Exception e) {
					e.printStackTrace();
					result.put("code", "0001");
					result.put("message", "渠道商(" + oneByParams.getChannelName() + ")禁用失败，原因：" + e.getMessage());
					return result;
				}
			}
		}
	}

	/**
	 * @param id 渠道商主键id
	 * @return
	 * @description 根据渠道商主键id查询一个，用于修改回显【2.2-服务包配置需求】
	 * @author wkangle
	 * @time 2022/03/04 0004 8:53
	 * @exception/throws
	 */
	@Override
	public ChannelVo queryOne(Long id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		ChannelEntity entity = this.getOneByParams(params);

		ChannelVo vo = new ChannelVo();
		vo.setId(entity.getId());
		vo.setClientId(entity.getClientId());
		vo.setChannelName(entity.getChannelName());
		vo.setChannelCode(entity.getChannelCode());
		vo.setServiceItem(entity.getServiceItem());
		vo.setPk(entity.getPk());
		vo.setSk(entity.getSk());
		vo.setStatus(entity.getStatus());

		vo.setIsDelete(entity.getIsDelete());
		vo.setCreater(entity.getCreater());
		vo.setCreateTime(entity.getCreateTime());
		vo.setUpdater(entity.getUpdater());
		vo.setUpdateTime(entity.getUpdateTime());


		List<ChannelDataEntity> channelDataEntityList = channelDataDao.selectChannelDataById(id.toString());
		vo.setChannelDataEntityList(channelDataEntityList);
		return vo;
	}

	/**
	 *
	 * @author WANGCONG
	 * 2022年4月13日下午17:16:09
	 * @desc 根据救援单渠道来源查询对应接口信息
	 */
	@Override
	public ChannelDataEntity findChannelDataByParam(Map<String, String> channelMap) {
		return channelDataDao.findChannelDataByParam(channelMap);
	}

	/**
    *
    * @author WANGCONG
    * 2022年4月14日上午10:45:39
    * @desc 渠道商clientId校验唯一性
    */
	@Override
	public String getChannelClientId(String clientId, String id) {
		 
		Map<String, String> param = new HashMap<String, String>();
		param.put("clientId", clientId);
		param.put("id", id);
		int count = channeDao.getChannelClientId(param);
		return count>0 ? "1" : "0"; //有就是1，没有就是0
	}


}




